package net.zjitc.springboot_mybatisplus.controller;

import net.zjitc.springboot_mybatisplus.dao.BookDao;
import net.zjitc.springboot_mybatisplus.domain.Book;
import net.zjitc.springboot_mybatisplus.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class BookController {
    @Autowired
    private BookService bookService;

    @Autowired
    private BookDao bookDao;

    @GetMapping("/tests")
    public String test(Model model){  //传递一个参数修改模板
        model.addAttribute("messages", bookService.getById(1)); //attributeName和html中的%{}名字相对应
        return "book";
    }

    @GetMapping("/books")
    public String book(Model model){
        //查看所有的书籍信息
        List<Book> books = bookService.list();

        //打印书籍信息
        System.out.println("打印书籍信息"+books.size());
        books.forEach(System.out::println);

        //把书籍信息添加进model
        model.addAttribute("books", books);

        return "book-list";
    }

    //显示表单内容
    @GetMapping("/book-form")
    public String addBook(Model model){
        model.addAttribute("book", new Book());
        return "book-form";
    }

    //处理表单内容
    @PostMapping("/submit-book")
    public String submitBook(Model model, @ModelAttribute Book book){
        //model(book) -> view -> controller
        //将填写的书籍上传到数据库中
        bookDao.insert(book);  //基于mybatisplus的sql语句

        //将提交的数据信息传送到结果页面
        model.addAttribute("book", book);
        //model.addattribute(key,value),第一个book是页面里的对象，需要我们传递的key,后面的book事传递的book数值
        return "book-result";
    }

    @GetMapping("view-book")
    //根据Id查询书籍详情
    public String SearchBook(Model model, @RequestParam Integer id){
        //根据Id查询数据
        Book book = bookDao.selectById(id);
        if(book == null){
            return "error";
        }
        model.addAttribute("book", book);
        return "book-detail";
    }

    @GetMapping("/book/edit/{id}")   //和book-detail.html中的编辑按钮保持一致
    public String editForm(Model model, @PathVariable Integer id){
        Book book = bookDao.selectById(id);
        if(book == null){
            return "error";
        }
        model.addAttribute("book", book);
        return "book-edit";
    }

    @PostMapping("/book/update")
    public String updateBook(Model model, @ModelAttribute Book book){
        //上传的是一整个对象 而不是单独的某一个属性
        bookDao.updateById(book);
        model.addAttribute("book", book);
        return "book-detail";
    }
    @PostMapping("/delete-book")
    public String deleteBook(@RequestParam("id") Integer id){
        boolean deleted = bookService.removeById(id);
        if(deleted){
            return "success";
        }else{
            return "error";
        }

    }
}
